import json

from django.http import JsonResponse
from Book import models
import time, datetime


class Book:

    # 返回图书总列表
    @staticmethod
    def all_book_list(request):
        if request.method == 'POST':
            book_list = models.Books.objects.all().order_by('-be_collects')
            books_list = []
            for b in book_list:
                book_obj = {}
                book_obj['title'] = b.title
                book_obj['pub_date'] = b.pub_date
                book_obj['pub_name'] = b.pub_name
                book_obj['ISBN_Nun'] = b.ISBN_Num
                try:
                    authors = models.Books.objects.get(title=b.title).authors.all()
                except Exception as e:
                    return JsonResponse({
                        "status": 7,
                        "message": "图书不存在"
                    })
                authors_list = []
                for a in authors:
                    authors_obj = {}
                    authors_obj['name'] = a.name
                    authors_obj['introduction'] = a.introduction
                    authors_obj['book_count'] = a.book_count
                    authors_obj['age'] = a.age
                    authors_list.append(authors_obj)
                book_obj['authors_list'] = authors_list
                books_list.append(book_obj)
            return JsonResponse({
                "error_code": 0,
                "message": "get list success",
                "books_list": books_list
            })

    # 返回关键词总列表
    @staticmethod
    def all_tag_list(request):
        if request.method == 'POST':
            tag_list = models.tag.objects.all().order_by('-be_related')
            tags_list = []
            for b in tag_list:
                tag_obj = {}
                tag_obj['word'] = b.word
                tag_obj['be_related'] = b.be_related
            return JsonResponse({
                "error_code": 0,
                "message": "get list success",
                "tags_list": tags_list,
            })

    @staticmethod
    def according_author(request):
        data = json.loads(request.body)
        author_list = data.get('author_list')
        final_set = models.Books.objects.all()
        for a in author_list:
            final_set = final_set.filter(authors__name__icontains=a)
        final_list = list(final_set)
        return JsonResponse({
            "error_code": 0,
            "message": "search success",
            "final_list": final_list,
        })

    @staticmethod
    def according_title(request):
        data = json.loads(request.body)
        keyword = data.get('title_name')
        final_set = models.Books.objects.filter(title__icontains=keyword)
        final_list = list(final_set)
        return JsonResponse({
            "error_code": 0,
            "message": "search success",
            "final_list": final_list,
        })

    @staticmethod
    def according_tags(request):
        data = json.loads(request.body)
        tags_list = data.get('tags_list')
        final_set = models.Books.objects.all()
        for t in tags_list:
            final_set = final_set.filter(tags__word__icontains=t)
        final_list = list(final_set)
        return JsonResponse({
            "error_code": 0,
            "message": "search success",
            "final_list": final_list,
        })

    @staticmethod
    def follow_book(request):
        data = json.loads(request.body)
        book_obj = models.Books.objects.filter(ISBN_Num=data.get('ISBN_Num')).first()
        if book_obj is None:
            return JsonResponse({
                "error_code": 9,
                "message": "查无此书",
            })
        else:
            user_obj = models.UserInfo.objects.get(user__id=request.user.id)
            follow_obj = models.Book_Follow.objects.filter(Follower=user_obj, Followed=book_obj).first()
            if follow_obj is None:
                models.Book_Follow.objects.create(
                    Followed=book_obj,
                    Follower=user_obj,
                )
                return JsonResponse({
                    "error_code": 0,
                    "message": "关注成功",
                })
            else:
                return JsonResponse({
                    "error_code": 10,
                    "message": "已经关注过了",
                })

    @staticmethod
    def unfollow_book(request):
        data = json.loads(request.body)
        book_obj = models.Books.objects.filter(ISBN_Num=data.get('ISBN_Num')).first()
        if book_obj is None:
            return JsonResponse({
                "error_code": 9,
                "message": "查无此书",
            })
        else:
            user_obj = models.UserInfo.objects.get(user__id=request.user.id)
            follow_obj = models.Book_Follow.objects.filter(Follower=user_obj, Followed=book_obj).first()
            if follow_obj is None:
                return JsonResponse({
                    "error_code": 11,
                    "message": "已取消关注",
                })
            else:
                models.Book_Follow.objects.get(Follower=user_obj, Followed=book_obj).delete()
                return JsonResponse({
                    "error_code": 0,
                    "message": "取消关注成功",
                })

    @staticmethod
    def get_follow_list(request):
        user_obj = models.UserInfo.objects.get(user__id=request.user.id)
        book_list = models.Book_Follow.objects.filter(Follower=user_obj).order_by('-be_collects')
        for b in book_list:
            book_obj = {}
            book_obj['title'] = b.title
            book_obj['pub_date'] = b.pub_date
            book_obj['pub_name'] = b.pub_name
            book_obj['ISBN_Nun'] = b.ISBN_Num
            try:
                authors = models.Books.objects.get(title=b.title).authors.all()
            except Exception as e:
                return JsonResponse({
                    "status": 7,
                    "message": "图书不存在"
                })
            authors_list = []
            for a in authors:
                authors_obj = {}
                authors_obj['name'] = a.name
                authors_obj['introduction'] = a.introduction
                authors_obj['book_count'] = a.book_count
                authors_obj['age'] = a.age
                authors_list.append(authors_obj)
            book_obj['authors_list'] = authors_list
            book_list.append(book_obj)
        return JsonResponse({
            "error_code": 0,
            "message": "get follow list success",
            "books_list": book_list,
        })

    @staticmethod
    def add_book(request):
        data = json.loads(request.body)
        ISBM_Num = data.get('book_ISBM_Num').strip()
        book_obj = models.Books.objects.filter(ISBM_Num=ISBM_Num).first()
        if book_obj is None:
            title = data.get('title').strip()
            book_connect = data.get('book_connect').strip()
            pub_date1 = data.get('pub_date')
            fmt = '%Y-%m-%d'
            pub_date2 = time.strptime(pub_date1, fmt)
            year, month, day = pub_date2[:3]
            pub_date = datetime.date(year, month, day)
            # book_image = data.get('book_image') # ???
            pub_name = data.get('pub_name').strip()
            new_book_obj = models.Books.objects.create(
                ISBN_Num=ISBM_Num,
                title=title,
                book_connect=book_connect,
                pub_name=pub_name,
                be_collects=0,
                pub_date=pub_date,
            )
            authors_list = data.get('authors_list')
            for a in authors_list:
                author_obj = models.Author.objects.filter(name=a.name).first()
                if author_obj is None:
                    new_author_obj = models.Author.objects.create(
                        name=a.name,
                        introduction=a.introduction,
                        book_count=1,
                        age=a.age,
                    )
                    new_book_obj.authors.add(new_author_obj)
                else:
                    author_obj.update(book_count=author_obj.book_count + 1)
                    author_obj.save()
                    new_book_obj.authors.add(author_obj)
            tags_list = data.get('tags_list')
            for t in tags_list:
                tag_obj = models.tag.objects.filter(word=t.word).first()
                if tag_obj is None:
                    new_tag_obj = models.tag.objects.create(
                        word=t.word,
                        be_related=1,
                    )
                    new_book_obj.tags.add(new_tag_obj)
                else:
                    tag_obj.update(be_related=tag_obj.be_related + 1)
                    tag_obj.save()
                    new_book_obj.tags.add(tag_obj)
        else:
            return JsonResponse({
                "error_code": 12,
                "message": "ISBN号已存在,加入失败",
            })

    @staticmethod
    def delete_book(request):
        data = json.loads(request.body)
        ISBN_Num = data.get('ISBN_Num')
        delete_book_obj = models.Books.objects.filter(ISBN_Num=ISBN_Num).first()
        if delete_book_obj is None:
            return JsonResponse({
                "error_code": 13,
                "message": "图书已删除,请勿重复操作",
            })
        authors_list = data.get('authors_list')
        for a in authors_list:
            name = a.name
            author_obj = models.Author.objects.get(name=name)
            if author_obj.book_count == 1:
                models.Author.objects.get(name=name).delete()
            else:
                author_obj.update(book_count=author_obj.book_count - 1)
                author_obj.save()
        tags_list = data.get('tags_list')
        for t in tags_list:
            word = t.word
            tag_obj = models.Author.objects.get(word=word)
            if tag_obj.be_related == 1:
                models.tag.objects.get(word=word).delete()
            else:
                tag_obj.update(be_related=tag_obj.be_related - 1)
                tag_obj.save()
        models.Books.objects.get(ISBN_Num=ISBN_Num).delete()
        return JsonResponse({
            "error_code": 0,
            "message": "删除成功",
        })